import { createStore } from 'vuex'
import { ListItem } from '@/interfaces'

interface State {
  visible: boolean
  listHistory: ListItem[],
  user: {
    isLogin: boolean,
    user: string
  }
}
const myPlugin = (store: any) => {
  // 当 store 初始化后调用
  store.subscribe((mutation: any, state: State) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    localStorage.setItem('listHistory', JSON.stringify(state.listHistory))
  })
}

export default createStore<State>({
  state: {
    // loading 状态
    visible: false,
    // 历史记录
    listHistory: JSON.parse(localStorage.getItem('listHistory') as string) || [],
    user: {
      isLogin: localStorage.getItem('token') ? true : false,
      user: ''
    }
  },
  mutations: {
    setVisible(state, bool: boolean) {
      state.visible = bool
    },
    addListHistory(state, payload: ListItem) {
      state.listHistory.unshift(payload)
    },
    setUser(state, payload) {
      Object.assign(state.user, payload)
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [
    myPlugin
  ]
})
